package com.lczyfz.wisdom.common.utils;

import com.lczyfz.wisdom.common.config.Global;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @author Lczy-Huang
 * @version 1.0
 * @classname RedisUtil
 * @description 连接redis获取数据
 * @date 2018/11/12 14:03
 **/
public class RedisUtil {
    private static String _addr = Global.getConfig("RedisIP");
    private static int _port = Integer.valueOf(Global.getConfig("RedisPort"));
    private static String _auth = Global.getConfig("RedisAuth");
    private static int _selectDb = Integer.valueOf(Global.getConfig("RedisDb"));
    private static int _maxActive = Integer.valueOf(Global.getConfig("RedisMaxActive"));
    private static int _maxIdea = Integer.valueOf(Global.getConfig("RedisMaxIdle"));
    private static int _maxWait = Integer.valueOf(Global.getConfig("RedisMaxWait"));
    private static int _timeOut = Integer.valueOf(Global.getConfig("RedisTimeOut"));
    private static boolean _testOnBorrow = true;
    private static JedisPool _jedisPool = null;

    /*
     * @description 初始化连接池，在tomcat启动阶段完成
     * @author Huang Bing
     * @time 2018/11/12 14:50
     */
    static {
        try{
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(_maxActive);
            config.setMaxIdle(_maxIdea);
            config.setMaxWaitMillis(_maxWait);
            config.setTestOnBorrow(_testOnBorrow);
            _jedisPool = new JedisPool(config,_addr,_port,_timeOut,_auth,_selectDb);
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    /*
     * @description 获得redis 实例，所有调用该方法都必须等上个调用完成才能进行分配
     * @params []
     * @return redis.clients.jedis.Jedis
     * @author Huang Bing
     * @time 2018/11/12 14:52
     */
    public synchronized static Jedis getJedis(){
        try{
            if(_jedisPool != null){
                Jedis resource = _jedisPool.getResource();
                return resource;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /*
     * @description 释放资源
     * @params [jedis]
     * @return void
     * @author Huang Bing
     * @time 2018/11/12 14:54
     */
    public static void returnResource(final Jedis jedis){
        if(jedis != null) {
            _jedisPool.returnResource(jedis);
        }
    }

}

